//
//  UIView+init.m
//  HWTV
//
//  Created by gengjie on 2016/10/26.
//  Copyright © 2016年 yijie. All rights reserved.
//

#import "UIView+init.h"


#pragma mark - SelfRotationHelper

@interface SelfRotationHelper : NSObject<CAAnimationDelegate>

@property (weak, nonatomic) UIView *view;

@end

@implementation SelfRotationHelper

#pragma mark - I/F

+ (instancetype)helperWithView:(UIView *)view
{
    SelfRotationHelper *helper = [[SelfRotationHelper alloc] init];
    helper.view = view;
    return helper;
}

#pragma mark - CAAnimationDelegate

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
        // restart animation in case of animation stopped after view is out of screen
    if (self.view.window){
        [self.view addAnimation:anim.duration];
    }
}

@end
static NSString *const AnimationKey = @"rotate-layer";

@implementation UIView (init)
/**
 *  快速创建的类方法
 *
 */
+ (instancetype)hw_viewFromXib
{
    return [[UIView alloc]init];
}


/**
 添加view动画

 @param period 动画时间
 */
- (void)addAnimation:(CFTimeInterval)period{
    
    if (![self.layer animationForKey:AnimationKey]){
        CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
        animation.duration = period;
        animation.repeatCount = HUGE_VALF;
        animation.fromValue = [NSNumber numberWithFloat:0];
        animation.toValue = [NSNumber numberWithFloat:2 * M_PI];
//        animation.delegate = [SelfRotationHelper helperWithView:self];
        [self.layer addAnimation:animation forKey:AnimationKey];
    }
    
}
@end
